Skip to content

Fix Dict.has evaluating its key before its dict - #9544

Merged
cknitt merged 1 commit into
masterfrom
dict-has-order
Dec 6, 2026
Merged

cknitt merged 1 commit into
masterfrom
dict-has-order

Conversation

@cknitt

@cknitt cknitt commented Dec 6, 2026

Copy link
Copy Markdown
Member

Fixes #9222.

Dict.has(d, k) compiles to k in d, and JavaScript evaluates the key first. ReScript evaluates arguments left to right, so when both arguments had side effects, they ran in the wrong order.

Now, when the order can be observed, the dict is evaluated first, into a temporary:

let bothEffects = (d: dict<int>, k) => Dict.has(eff("dict", d), eff("key", k))
// before
return eff("key", k) in eff("dict", d);

// after
let tmp = eff("dict", d);
return eff("key", k) in tmp;

The output stays k in d when either argument is a constant or a variable nothing assigns, or when neither has side effects. So d->Dict.has("a"), d->Dict.has(k) and eff(d)->Dict.has("a") are unchanged, and no existing test output changes.

How

The fix is in the JavaScript compilation, where call arguments are already held in order (delay_safe, evaluate_now). The check is a new order_matters helper, shared with hold_obj_args, which made the same check for the optional fields of an @obj external.

Index reads count as pure here, as they do for @obj fields. A getter or a Proxy can therefore still see the key read first: Dict.has(o["x"], o["y"]) keeps o["y"] in o["x"], without a temporary. This is deliberate.

The conditional key from the issue's comment was already fixed by #9428.

Test

dict_has_order_test logs the effects of both arguments and checks their order. It covers:

  • a key or dict that reads state the other one changes;
  • assignable locals;
  • a try as the key;
  • a nested Dict.has;
  • the common shapes, which keep their output.

The order tests fail on master.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq

Why:
    `Dict.has(d, k)` compiles to `k in d`, and JS evaluates the key
    first. ReScript evaluates arguments left to right, so the effects of
    the two arguments ran in the wrong order. Fixes #9222.

When the order can be seen, the dict is now evaluated first, into a
temporary. The output stays `k in d` when either argument is a constant
or a variable nothing assigns, or when neither has side effects.

JS modified (Dict.has whose arguments must run in order):
Example:
    let eff: (string, 'a) => 'a = %raw(`function (s, v) { log.push(s); return v }`)
    let bothEffects = (d: dict<int>, k) => Dict.has(eff("dict", d), eff("key", k))
    let dicts = ref(dict{"a": 1})
    let dictReadsState = (other: dict<int>) =>
      Dict.has(
        dicts.contents,
        {
          dicts := other
          eff("key", "a")
        },
      )
Before (js):
    function bothEffects(d, k) {
      return eff("key", k) in eff("dict", d);
    }

    function dictReadsState(other) {
      return (dicts.contents = other, eff("key", "a")) in dicts.contents;
    }
After (js):
    function bothEffects(d, k) {
      let tmp = eff("dict", d);
      return eff("key", k) in tmp;
    }

    function dictReadsState(other) {
      let tmp = dicts.contents;
      return (dicts.contents = other, eff("key", "a")) in tmp;
    }

JS modified (Dict.has whose order cannot be seen):
Example:
    let constantKey = (d: dict<int>) => eff("dict", d)->Dict.has("a")
    let variableDict = (d: dict<int>) => d->Dict.has(eff("key", "a"))
    let variables = (d: dict<int>, k) => d->Dict.has(k)
Before (js): unchanged
    function constantKey(d) {
      return "a" in eff("dict", d);
    }

    function variableDict(d) {
      return eff("key", "a") in d;
    }

    function variables(d, k) {
      return k in d;
    }
After (js): unchanged
    function constantKey(d) {
      return "a" in eff("dict", d);
    }

    function variableDict(d) {
      return eff("key", "a") in d;
    }

    function variables(d, k) {
      return k in d;
    }

Review: Why in JS compilation and not in Lambda? Call arguments are already held there in order, with `delay_safe` and `evaluate_now`. `hold_dict_has` reuses them. It shares the new `order_matters` with `hold_obj_args`, which made the same check for the optional fields of an `@obj` external.
Review: Can a getter still see the key read first? Yes. Index reads count as pure, as for `@obj` fields, so `Dict.has(o["x"], o["y"])` keeps `o["y"] in o["x"]` and gets no temporary. This is deliberate.
Review: What about the conditional key from the issue's comment? #9428 fixed it: `d->Dict.has(c ? "a" : "b")` prints `(c ? "a" : "b") in d`, and `printer_operand_levels_test` covers it.
Review: Does other output change? No. The runtime, Belt and every test's JavaScript compile as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Kbf3gHZYwA1rq7zbk3dhQq
Signed-off-by: Christoph Knittel <ck@cca.io>
@github-actions

github-actions Bot commented Dec 6, 2026

Copy link
Copy Markdown

Changelog

🐛 Bug fix

  • Fix Dict.has evaluating its key before its dict.

Semantic Diff

1 commit · Full page

Fix Dict.has evaluating its key before its dict

e8d8557 · cknitt + Claude · Dec 06, 2026, 08:25 UTC

Why

Dict.has(d, k) compiles to k in d, and JS evaluates the key first. ReScript evaluates arguments left to right, so the effects of the two arguments ran in the wrong order. Fixes #9222.

When the order can be seen, the dict is now evaluated first, into a temporary. The output stays k in d when either argument is a constant or a variable nothing assigns, or when neither has side effects.

JS modified (Dict.has whose arguments must run in order)

let eff: (string, 'a) => 'a = %raw(`function (s, v) { log.push(s); return v }`)
let bothEffects = (d: dict<int>, k) => Dict.has(eff("dict", d), eff("key", k))
let dicts = ref(dict{"a": 1})
let dictReadsState = (other: dict<int>) =>
  Dict.has(
    dicts.contents,
    {
      dicts := other
      eff("key", "a")
    },
  )

js

 function bothEffects(d, k) {
-  return eff("key", k) in eff("dict", d);
+  let tmp = eff("dict", d);
+  return eff("key", k) in tmp;
 }
 
 function dictReadsState(other) {
-  return (dicts.contents = other, eff("key", "a")) in dicts.contents;
+  let tmp = dicts.contents;
+  return (dicts.contents = other, eff("key", "a")) in tmp;
 }

JS modified (Dict.has whose order cannot be seen)

let constantKey = (d: dict<int>) => eff("dict", d)->Dict.has("a")
let variableDict = (d: dict<int>) => d->Dict.has(eff("key", "a"))
let variables = (d: dict<int>, k) => d->Dict.has(k)

js · Before and After are equal · unchanged

function constantKey(d) {
  return "a" in eff("dict", d);
}

function variableDict(d) {
  return eff("key", "a") in d;
}

function variables(d, k) {
  return k in d;
}

Review

  • Why in JS compilation and not in Lambda? Call arguments are already held there in order, with delay_safe and evaluate_now. hold_dict_has reuses them. It shares the new order_matters with hold_obj_args, which made the same check for the optional fields of an @obj external.
  • Can a getter still see the key read first? Yes. Index reads count as pure, as for @obj fields, so Dict.has(o["x"], o["y"]) keeps o["y"] in o["x"] and gets no temporary. This is deliberate.
  • What about the conditional key from the issue's comment? Print the operands of in and loop headers with the levels JS needs #9428 fixed it: d->Dict.has(c ? "a" : "b") prints (c ? "a" : "b") in d, and printer_operand_levels_test covers it.
  • Does other output change? No. The runtime, Belt and every test's JavaScript compile as before.

@codecov

codecov Bot commented Dec 6, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 82.68%. Comparing base (daa4f2d) to head (e8d8557).

Files with missing lines Patch % Lines
compiler/backend/lam_compile.ml 90.90% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master    #9544   +/-   ##
=======================================
  Coverage   82.68%   82.68%           
=======================================
  Files         469      469           
  Lines       66582    66588    +6     
=======================================
+ Hits        55052    55058    +6     
  Misses      11530    11530           
Files with missing lines Coverage Δ
compiler/backend/lam_compile_external_obj.ml 96.77% <100.00%> (+1.25%) ⬆️
compiler/backend/lam_compile_primitive.ml 81.79% <ø> (ø)
compiler/backend/lam_compile.ml 92.28% <90.90%> (-0.02%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@pkg-pr-new

pkg-pr-new Bot commented Dec 6, 2026

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@9544

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@9544

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@9544

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@9544

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@9544

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@9544

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@9544

commit: e8d8557

@github-actions

github-actions Bot commented Dec 6, 2026

Copy link
Copy Markdown

✅ Compiler benchmarks

Allocated words

In total: 656,461,005 → 656,461,766 (±0.00%).

Generated projects: 628,526,307 → 628,527,875 (±0.00%).

None of the 265 benchmarks changed by 0.1% or more.

Instructions

In total: 8,976,406,297 → 8,976,462,256 (±0.00%).

None of the 33 benchmarks changed by 0.1% or more.

Output size

In total: 27,594,926 → 27,595,129 (±0.00%).

None of the 13 benchmarks changed by 0.1% or more.

Pull request e8d8557 compared with base daa4f2d in this run.

@github-actions

github-actions Bot commented Dec 6, 2026

Copy link
Copy Markdown

@cknitt

cknitt commented Dec 6, 2026

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Dec 6, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-12-06T10:03:52.117099Z e8d8557 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: e8d8557f8c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@cknitt
cknitt marked this pull request as ready for review December 6, 2026 10:17
@cknitt
cknitt requested a review from cristianoc December 6, 2026 10:17

@cristianoc cristianoc left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The regression tests cover ordinary observable effects and mutable operands. The documented getter/Proxy case remains intentionally outside this fix, consistent with the existing purity model for property reads.

@cknitt
cknitt merged commit e7c0f3f into master Dec 6, 2026
22 checks passed
@cknitt
cknitt deleted the dict-has-order branch December 6, 2026 15:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Dict.has runs its arguments in the wrong order

2 participants